﻿using System;
using System.Collections.Generic;
using System.Web;
using Ultimus.WFServer;
using System.IO;
using System.Data;
using System.Text;
using System.Collections;
using App.Data;

namespace Task
{
    /// <summary>
    ///ESI_TBMapping 的摘要说明
    /// </summary>
    public class ESISyncTableLogic
    {
        public ESISyncTableLogic()
        {

        }

        public bool SyncTable(string taskId)
        {
            string processName = "";
            string stepName = "";
            log("===========================同步TaskId" + taskId + "开始===========================");
            //1.加载任务
            Ultimus.WFServer.Task task = new Ultimus.WFServer.Task();
            bool flag = task.InitializeFromTaskId(taskId);
            if (flag)
            {
                log("获取task成功:" + taskId);
                processName = task.strProcessName;
                stepName = task.strStepName;
                log("流程名" + task.strProcessName);
                log("步骤名" + task.strStepName);
                log("实例号" + task.nIncidentNo);
                log("任务接收人" + task.strAssignedToUser);
            }
            else
            {
                log("获取task失败:" + taskId);
                return false;
            }

            //2.取配置表的数据

            string sql = string.Format("select distinct Table_Name from T_ESI_TB_CONFIG where ProcessName='{0}' and StepName='{1}';", processName, stepName);
            DataTable dtTables = DataAccess.Instance("BusinessDB").ExecuteDataTable (sql);

            //3.把数据同步到相应表中
            object ret = null;
            string error = "";
            for (int i = 0; i < dtTables.Rows.Count; i++) //对表做循环
            {
                DataRow row = dtTables.Rows[i];
                try
                {
                    log("写入表" + row["Table_Name"].ToString() + "开始");
                   
                    sql = string.Format("select * from T_ESI_TB_CONFIG where ProcessName='{0}' and StepName='{1}' and Table_name='{2}' order by autoid;", processName, stepName, row["Table_Name"].ToString());
                    DataTable dtColumns = DataAccess.Instance("BusinessDB").ExecuteDataTable(sql);

                    sql = "insert into {0}({1}) ";
                    StringBuilder sbCols = new StringBuilder();
                    StringBuilder sbVars = new StringBuilder();
                    bool hasIncident = false;
                    object incident = null;
                    bool isSubTable = false;
                    int count = 0;
                    Dictionary<string, object> dicts = new Dictionary<string, object>();
                    int subTableRows = 0;
                    foreach (DataRow rowCol in dtColumns.Rows) //对所有的列做循环
                    {
                        //表中是否有Incident这个字段
                        if (rowCol["Column_name"].ToString().ToUpper() == "INCIDENT")
                        {
                            hasIncident = true;
                            task.GetVariableValue("SYS_INCIDENT", out incident, out error);
                        }
                        if (rowCol["Is_SubTable"].ToString().ToUpper() == "1")
                        {
                            isSubTable = true;
                        }
                        //绑定列名
                        sbCols.Append(rowCol["Column_name"].ToString() + ",");
                        //绑定电子表格变量
                        if (task.GetVariableValue(rowCol["SSL_VarName"].ToString(), out ret, out error))
                        {
                            if (isSubTable) //子表 
                            {
                                dicts.Add(rowCol["Column_name"].ToString(), ret);
                                if (ret.GetType().IsArray)
                                {
                                    if (subTableRows < ((Array)ret).Length)
                                    {
                                        subTableRows = ((Array)ret).Length;
                                    }
                                }
                            }
                            else
                            {
                                if (count == 0)
                                {
                                    sql = sql + " values({2});";
                                }
                                sbVars.Append("'" + ret.ToString() + "',");
                            }
                        }
                        else
                        {
                            log("获取变量" + rowCol["SSL_VarName"].ToString() + "失败");
                        }
                        count++;
                    }
                    string deleteSql = "";
                    if (hasIncident) //有incident字段，每次覆盖更新
                    {
                        deleteSql = "delete from {0} where INCIDENT=" + incident.ToString() + ";";
                    }
                    if (isSubTable) //生成子表的sql
                    {
                        StringBuilder subSql = new StringBuilder();
                        for (int j = 0; j < subTableRows; j++) //子表的行
                        {
                            StringBuilder colSql = new StringBuilder();
                            int k = 0;
                            foreach (string str in dicts.Keys) //子表的列
                            {
                                object value = null;
                                dicts.TryGetValue(str, out value);
                                if (value is Array)
                                {
                                    object val = ((Array)value).GetValue(j);
                                    //第一列的值为null，那么跳过该行
                                    if (k == 0 && val == null)
                                    {
                                        colSql = new StringBuilder();
                                        break;
                                    }
                                    else
                                    {
                                        colSql.Append("'" + val.ToString() + "',");
                                        k++;
                                    }
                                }
                                else
                                {
                                    if (value != null)
                                    {
                                        colSql.Append("'" + value.ToString() + "',");
                                    }
                                }
                            }
                            if (colSql.Length > 0)
                            {
                                subSql.AppendFormat(sql, row["Table_Name"].ToString(), sbCols.ToString().TrimEnd(','));
                                subSql.AppendFormat("  values({0});", colSql.ToString().TrimEnd(','));
                            }
                        }
                        sql = string.Format(deleteSql, row["Table_Name"].ToString()) + subSql.ToString();
                    }
                    else //生成主表的sql
                    {
                        sql = string.Format(deleteSql + sql, row["Table_Name"].ToString(), sbCols.ToString().TrimEnd(','), sbVars.ToString().TrimEnd(','));
                    }

                    DataAccess.Instance("BusinessDB").ExecuteNonQuery(sql);
                    log("写入表" + row["Table_Name"].ToString() + "结束");
                }
                catch (Exception e)
                {
                    log("写入表" + row["Table_Name"].ToString() + "失败sql:" + sql + "错误信息：" + e.Message);
                    return false;
                }

            }

            log("===========================同步TaskId" + taskId + "结束===========================");
            return true;
        }


        void log(string msg)
        {
            this.log("", true, msg);
        }
        private string pthLog = @"C:\esiLog " + System.DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        private string isDebug = "Debug";
        public void log(string strPath, bool booDebug, string strInfo)
        {
            try
            {
                //初始化写是否写日志标志变量
                bool booFlg = true;

                //根据不同的情况改变是否写日志标志变量的值
                if (!booDebug)
                {
                    booFlg = true;
                }
                else
                {
                    if (this.isDebug == "Debug")
                    {
                        booFlg = true;
                    }
                    else
                    {
                        booFlg = false;
                    }
                }

                //根据是否写日志标志变量的取值,来执行日志写入
                if (booFlg)
                {
                    if (strPath.Trim() == "" || strPath == string.Empty)
                    {
                        strPath = this.pthLog;
                    }

                    FileInfo fleLog = new FileInfo(strPath);
                    StreamWriter steWrt = fleLog.AppendText();
                    steWrt.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]: " + strInfo);
                    steWrt.Close();
                }
            }
            catch (Exception ee)
            {
                string aa = ee.Message;
            }
        }
    }
}